package com.habdqn.easybuy.web.front;

import com.habdqn.easybuy.entity.User;
import com.habdqn.easybuy.exception.LoginException;
import com.habdqn.easybuy.service.UserService;
import com.habdqn.easybuy.service.impl.UserServiceImpl;
import com.habdqn.easybuy.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Xing.Jiejian
 * @date 2020/11/28
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String veryCode = request.getParameter("veryCode");
        String verifyCode = (String) session.getAttribute("VerifyCode");

        if (!StringUtils.equalsIgnoreCase(verifyCode,veryCode)){
            request.setAttribute("errorMsg","验证码错误！");
            request.getRequestDispatcher("/WEB-INF/front/login.jsp").forward(request,response);
        }else{
            UserService userService = new UserServiceImpl();
            try {
                User user = userService.login(username,password);
                // 没有异常则表示登录成功，用户放入会话中
                session.setAttribute("currentUser",user);
                // 判断是否有原页面
                String localPath = (String) session.getAttribute("localPath");
                if (StringUtils.isNotBlank(localPath)){
                    session.removeAttribute("localPath");
                    response.sendRedirect(localPath);
                }else {
                    response.sendRedirect(request.getContextPath() + "/index");
                }
            } catch (LoginException e){
                request.setAttribute("errorMsg",e.getMessage());
                request.getRequestDispatcher("/WEB-INF/front/login.jsp").forward(request,response);
            }

        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/front/login.jsp").forward(request,response);
    }
}
